#include "service_timer.h"
#include "service.h"
#include <event.h>
ServiceTimer::ServiceTimer(Service * service, ServiceTimerHandler * handler, int timeOut, bool repid)
{
	m_repid = repid;
	m_service = service;
	m_handler = handler;
	m_timeout = timeOut;
	int seconds = timeOut / 1000;
	int uSeconds = (timeOut - seconds * 1000) * 1000;
	timeval val = { seconds, uSeconds };
	m_tmr = evtimer_new(service->getBase(), &ServiceTimer::onTimer, this);
	evtimer_add(m_tmr, &val);
}

void ServiceTimer::onTimer(int fd, short ev, void * args)
{
	ServiceTimer* timer = (ServiceTimer*)args;
	if (timer->m_repid) {
		int seconds = timer->m_timeout / 1000;
		int uSeconds = (timer->m_timeout - seconds * 1000) * 1000;
		timeval val = { seconds, uSeconds };
		evtimer_add(timer->m_tmr, &val);
	}
	timer->m_handler->onServiceTimer(timer);
}


ServiceTimer::~ServiceTimer()
{
	if (m_tmr) {
		evtimer_del(m_tmr);
		event_del(m_tmr);
	}
}

